import requests
from bs4 import BeautifulSoup

from mysql.mysqlconnect import MysqlConnect
from common.utils import *


def manageCity():
    url = 'http://www.maps7.com/china_province.php'
    selectors = 'body > div > div > a'
    selectors2 = 'h4'

    response = requests.get(url)
    soup = BeautifulSoup(response.text, 'html.parser')
    data = soup.select(selectors)

    sqlconnect = MysqlConnect()
    sql = 'insert into district(id, pid, name, en_name, type, hierarchy) values("{}", "{}", "{}", "{}", {}, {})'

    province = 1
    proid = '101'
    city = 1
    insert = sql.format('10' + str(province) if province < 10 else '1' + str(province), '1', '北京', 'Beijing', 1, 2)
    sqlconnect.sqlRun(insert)
    province += 1
    for item in data:
        # print(item)
        # 如果a标签下有h4标签，说明该a标签是省级区划信息
        if len(item.select(selectors2)) != 0:
            # 重置省份下市级索引
            city = 1
            name = item.get_text()
            names = trim_district_name(name)
            print(names, end='==>\n')
            proid = '10' + str(province) if province < 10 else '1' + str(province)
            insert = sql.format(proid, '1', names['name'], names['pinyin'], 1, 2)
            sqlconnect.sqlRun(insert)
            province += 1
        else:
            name = item.get_text()
            names = trim_district_name(name)
            print(names, end='==>\n')

            pid = '10' + str(province - 1) if province < 10 else '1' + str(province - 1)
            id = proid + ('0' + str(city) if city < 10 else '' + str(city))
            insert = sql.format(id, proid, names['name'], names['pinyin'], 2, 3)
            sqlconnect.sqlRun(insert)
            city += 1


if __name__ == '__main__':
    manageCity()
